package com.application.viewmodel;

import android.content.Context;
import android.widget.Toast;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import com.application.bean.Student;
import com.application.util.MySQLiteOpenHelper;

public class SQLiteUpdateViewModel extends ViewModel {
    public MutableLiveData<String> nameLiveData = new MutableLiveData<>();
    public MutableLiveData<String> numberLiveData = new MutableLiveData<>();
    public MutableLiveData<String> scoreLiveData = new MutableLiveData<>();
    private MySQLiteOpenHelper dbHelper;

    public void initDbHelper(Context context) {
        dbHelper = new MySQLiteOpenHelper(context);
    }

    public void updateData(Context context) {
        String name = nameLiveData.getValue();
        String number = numberLiveData.getValue();
        String score = scoreLiveData.getValue();
        if (name == null || number == null || score == null || name.isEmpty() || number.isEmpty() || score.isEmpty()) {
            Toast.makeText(context, "请完善学生信息", Toast.LENGTH_SHORT).show();
            return;
        }
        Student student = new Student();
        student.setName(name);
        student.setNumber(number);
        student.setScore(score);

        long rowId = dbHelper.updateData(student);
        if (rowId > 0) {
            Toast.makeText(context, "更新成功", Toast.LENGTH_SHORT).show();
            nameLiveData.setValue("");
            numberLiveData.setValue("");
            scoreLiveData.setValue("");
        } else {
            Toast.makeText(context, "没有数据被更新", Toast.LENGTH_SHORT).show();
        }
    }
}
